<template>
  <div class="main">
    <mine-title>新建自然语言处理分析</mine-title>
    <div class="main-body">

      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="识别类型：" prop="distinguishType">
          <el-radio-group @change="distinguishTypeChange" v-model="form.distinguishType" size="small">
            <el-radio-button label="single">单条</el-radio-button>
            <el-radio-button label="mult">多条</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="语言类型：" prop="languageType" key="languageType">
          <el-radio-group v-model="form.languageType" @change="handleLanguageType">
            <el-radio v-for="(item, index) in languageTypeList" :key="index" :label="item.id">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务名称：" prop="taskName" v-if="form.distinguishType == 'mult'" key="taskName">
          <el-input class="value short" size="small" placeholder="请输入内容" v-model="form.taskName" clearable></el-input>
        </el-form-item>
        <el-form-item label="任务类型：" prop="taskType" v-if="form.distinguishType == 'mult'" key="taskType">
          <el-select class="short" v-model="form.taskType" size="small" placeholder="请选择任务类型" clearable>
            <el-option v-for="(item, index) in taskTypeList" :key="index" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传数据：" :required="true" v-if="form.distinguishType == 'mult'" key="upload">
          <mine-upload ref="mineUpload" :fileType="multFileType" key="2"></mine-upload>
          <div style="margin-top: 16px;">
            <mine-button secondary size="mini" @click="downloadFile" :loading="downloading">下载模板<i class="iconfont icon-download-line is-right"></i></mine-button>
          </div>
        </el-form-item>

        <el-form-item label="文本内容：" v-if="form.distinguishType == 'single'" key="distinguishContent">
          <el-input type="textarea" :rows="4" @input="debounceSubmitSingle" placeholder="请输入内容" v-model="form.distinguishContent" :maxlength="20000" show-word-limit></el-input>
        </el-form-item>

        <el-form-item class="form-btn-row" label="" v-if="form.distinguishType == 'mult'">
          <mine-button v-if="analysisStatus != '1'" :type="analysisStatus == 0 ? 'primary' : 'success'" @click="submitMult">{{ analysisStatus == 0 ? "开始分析" : "下载结果" }}</mine-button>
        </el-form-item>
      </el-form>

      <div class="each-main-info" v-if="form.distinguishType == 'single'" v-loading="singleLoading">
        <div class="name"></div>
        <div class="value">
          <el-tabs v-model="singleResultType" type="card" @tab-click="singleResultTypeChange">
            <el-tab-pane v-for="(item, index) in singleResultTypeOptions" :label="item.label" :name="item.name" :key="index">
              <div class="single-show-area">
                <component ref="singleResultComponent" :is="item.component" :showData="singleResult"></component>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { debounce } from 'lodash';
import segmentationResults from "./components/segmentationResults";
import entityRecognition from "./components/entityRecognition";
import frequencyCount from "./components/frequencyCount";
import wordCloud from "./components/wordCloud";
import sentimentAnalysis from "./components/sentimentAnalysis";
import keywords from "./components/keywords";
import simWord from "./components/simWord";
export default {

  components: { segmentationResults, entityRecognition, frequencyCount, wordCloud, sentimentAnalysis, keywords, simWord, },

  data: function () {
    return {
      singleResultType: "first", // 单条分析结果展示的类型
      singleResultTypeOptions: [ // 单条分析结果展示的类型的选项卡
        { label: "分词结果", name: "first", component: "segmentationResults" },
        { label: "实体识别", name: "second", component: "entityRecognition" },
        { label: "词频统计", name: "third", component: "frequencyCount" },
        { label: "词云图", name: "fourth", component: "wordCloud" },
        { label: "关键字提取", name: "fifth", component: "keywords" },
        { label: "情感分析", name: "sixth", component: "sentimentAnalysis" },
        { label: '近义词识别', name: 'seventh', component: 'simWord' },
      ],
      taskTypeList: [ // 任务类型的备选项
        { id: 'segment', name: '分词' },
        { id: 'keyword', name: '关键词提取' },
        { id: 'sentiment', name: '情感分析' },
        { id: 'frequency', name: '词频' },
        { id: 'ner', name: '命名实体识别' },
        { id: 'simWord', name: '近义词识别' },
      ],
      languageTypeList: [
        { id: 'chinese', name: '中文' },
        { id: 'Japanese', name: '日文' },
        { id: 'english', name: '英文' },
        { id: 'german', name: '德文' },
      ],
      singleResult: {}, // 单条分析结果
      multUploadUrl: "openAbilityPlatformPredictTaskUpload", // 多条上传地址
      multFileType: ".txt", // 多条上传类型
      multUploadData: {}, // 多条上传时额外携带的数据
      analysisStatus: 0, // 多条分析状态
      multResultId: "", // 多条分析后的id
      form: {
        distinguishType: "single",
        taskName: "", // 多条分析的任务名称
        taskType: "", // 多条分析的任务类型
        distinguishContent: "", // 单条识别的内容
        languageType: '', // 语言类型
      },
      rules: {
        distinguishType: { required: true, message: '请选择任务类型', trigger: 'change' },
        taskName: { required: true, message: '请输入任务名称', trigger: 'blur' },
        taskType: { required: true, message: '请选择任务类型', trigger: 'blur' },
        languageType: { required: true, message: '请选择语言类型', trigger: 'change' },
      },
      downloading: false,
      singleLoading: false,
    }
  },

  methods: {
    // 下载模板
    async downloadFile () {
      this.downloading = true;
      try {
        await this.$store.dispatch('openAbilityPlatformPredictTaskGetFile', {
          projectType: 'nlp'
        });
      } catch (e) {
        console.error(e);
      }
      this.downloading = false;
    },

    // 单条多条分析切换时
    distinguishTypeChange: function () {
      this.singleResult = {};
      this.multUploadData = {};
      this.analysisStatus = 0;
      this.multResultId = "";
      this.form.taskName = "";
      this.form.taskType = "";
      this.form.distinguishContent = "";
      this.singleResultType = "first";
    },

    // 单条分析结果的展示类型发生改变
    singleResultTypeChange: function () {
      var _this = this;
      if (this.singleResultType == "fourth" || this.singleResultType == "sixth" || this.singleResultType == "third") {
        var index = this.singleResultType == "fourth" ? 3 : this.singleResultType == "sixth" ? 5 : 2;
        this.$nextTick(function () {
          _this.$refs.singleResultComponent[index].renderChart();
        })
      }
    },

    // 语言类型选择
    handleLanguageType () {
      if (this.form.distinguishType === 'single') {
        if (!this.$common.doSubmit('form', this)) return;
        if (this.form.distinguishContent) {
          this.submitSingle();
        }
      }
    },

    // 提交单条分析
    submitSingle: async function () {
      if (!this.form.distinguishContent) {
        this.$message({ type: 'warning', message: '分析的文本内容不能为空' });
        return;
      } else {
        if (!this.$common.doSubmit('form', this)) return;
        this.singleLoading = true;
        var send = {
          comment: this.form.distinguishContent,
          languageType: this.form.languageType,
        };
        try {
          const res = await this.$store.dispatch('openAbilityPlatformPredictTaskOnecommet', send);
          var result = res.data || {};
          if (result.success) {
            this.singleResult = result.data;
          } else {
            this.singleResult =  {};
          }
        } catch (e) {
          console.error(e);
          this.singleResult =  {};
        }
        this.singleLoading = false;
      }
    },

    // 多条上传成功 绑定任务
    uploadSuccess: async function (data) {
      this.$store.dispatch('openAbilityPlatformPredictTaskMuticommet', data);
      window.history.go(-1);
      /*
      const res = await this.$store.dispatch('openAbilityPlatformPredictTaskMuticommet', data);
      const result = res.data || {};
      if (result.success) {
        this.$refs.mineUpload.changeUploadStatus("success");
        this.analysisStatus = 2;
        var resultData = result.data || {};
        this.multResultId = resultData.id;
      } else {
        this.$refs.mineUpload.changeUploadStatus("error");
      }
      */
    },

    // 提交多条分析
    submitMult: async function () {
      if (this.analysisStatus == 0) { // 上传文件
        if (!this.$common.doSubmit('form', this)) return;
        if (!this.$refs.mineUpload.fileList.length) {
          this.$message({ type: "warning", message: "请选择上传的文件" });
          return false;
        }
        this.analysisStatus = 1;
        this.uploadFile();
      } else { // 下载文件结果
        const params = { id: this.multResultId };
        try {
          await this.$store.dispatch('openAbilityPlatformPredictTaskIdDownLoadResult', params);
        } catch (e) {
          console.error(e);
        }
      }
    },

    // 上传文件
    uploadFile: async function () {
      this.$refs.mineUpload.changeUploadStatus("uploading");
      const formData = new FormData();
      formData.append('File',  this.$refs.mineUpload.fileList[0].raw);
      formData.append("taskName", this.form.taskName);
      formData.append("taskType", this.form.taskType);
      formData.append("creator", this.$store.getters.userName || '');
      formData.append('languageType', this.form.languageType || '');
      try {
        const res = await this.$store.dispatch(this.multUploadUrl, formData);
        const result = res.data || {};
        if (result.success) {
					const parmas = result.data || {};
          this.uploadSuccess(parmas);
				}
      } catch (e) {
        console.error(e);
      }
    },

  },
  created () {
    this.debounceSubmitSingle = debounce(this.submitSingle, 500);

    // 设置面包屑导航
    this.$store.commit('SET_BREADCRUMB', [
      { title: '开放能力', path: '/openAbility' },
      { title: '新建自然语言处理分析', path: '' }
    ]);
  }
}
</script>

<style lang="less" scoped>
  .main {
    width: 100%;
    height: 100%;
  }

  .main-body {
    padding: 20px;
    background: #FFFFFF;
    box-shadow: 0px 0px 3px 0px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    font-family: PingFangSC-Regular;
  }

  .each-main-info {
    width: 100%;
    margin-bottom: 20px;
  }

  .each-main-info .name {
    width: 110px;
    display: inline-block;
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: rgba(0,0,0,0.75);
    text-align: right;
    line-height: 22px;
    font-weight: 400;
  }

  .each-main-info .value {
    width: calc(~"100% - 200px");
    display: inline-block;
  }

  .vertical-top {
    vertical-align: top;
  }

  .red {
    color: #F73D47;
    font-size: 18px;
    margin-right: 5px;
  }

  .short {
    width: 512px !important;
  }

  .single-show-area {
    width: calc(~"100% - 2px");
    height: 470px;
    border: solid 1px #e6e6e6;
    border-top: none;
  }

  /deep/ .el-tabs__header {
    margin: 0;
  }
</style>
